package com.jeesuite.bestpl.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeesuite.bestpl.api.IMessageService;
import com.jeesuite.bestpl.api.IPostService;
import com.jeesuite.bestpl.dao.entity.UserEntity;
import com.jeesuite.bestpl.dao.mapper.UserEntityMapper;
import com.jeesuite.bestpl.dto.Comment;
import com.jeesuite.bestpl.dto.Message;
import com.jeesuite.bestpl.dto.Page;
import com.jeesuite.bestpl.dto.PageMetaInfo;
import com.jeesuite.bestpl.dto.PageQueryParam;
import com.jeesuite.bestpl.dto.Post;
import com.jeesuite.bestpl.exception.JeesuiteBaseException;
import com.jeesuite.bestpl.security.PasswordUtils;
import com.jeesuite.bestpl.security.SecurityUtil;
import com.jeesuite.bestpl.service.UserService;
import com.jeesuite.filesystem.FSProvider;
import com.jeesuite.filesystem.FileType;
import com.jeesuite.filesystem.factory.FSClientFactory;

@Controller
@RequestMapping("/ucenter")
public class UCenterController {
	
	private static final String PNG = "png";
	
	private final static int DEFAULT_PAGE_SIZE = 10;
	private static List<String> allow_upload_suffix = new ArrayList<>(Arrays.asList("png","jpg","jpeg"));
	
	private FSProvider provider = FSClientFactory.build("qiniu", "bestpl");

	@Autowired
	private UserEntityMapper userMapper;
	private @Autowired IPostService postService;
	private @Autowired IMessageService messageService;
	private @Autowired UserService userService;
	
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(Model model){
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("ucenter"));
		
		return "ucenter/index";
	}
	
	@RequestMapping(value = "setting", method = RequestMethod.GET)
	public String setting(Model model){
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("ucenter"));
		
		return "ucenter/setting";
	}
	
	@RequestMapping(value = "messages", method = RequestMethod.GET)
	public String message(Model model){
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("ucenter"));
		List<Message> messages = messageService.findUserNotReadMessage(SecurityUtil.getLoginUserId());
		model.addAttribute("messages", messages);
		return "ucenter/message";
	}
	
	@RequestMapping(value = "myposts", method = RequestMethod.POST)
	public @ResponseBody Page<Post> myPosts(@RequestParam(value="page",required=false) int pageNo){
		PageQueryParam param = new PageQueryParam(pageNo <= 0 ? 1 : pageNo,DEFAULT_PAGE_SIZE);
		param.getConditions().put("userId", SecurityUtil.getLoginUserId());
		return postService.pageQueryPost(param);
	}
	
	@RequestMapping(value = "mycomments", method = RequestMethod.POST)
	public @ResponseBody Page<Comment> myComments(@RequestParam(value="page",required=false) int pageNo){
		//TODO
		Page<Comment> page = new Page<>(1, 10, 0, new ArrayList<>());
		return page;
	}
	
	@RequestMapping(value = "updatepwd", method = RequestMethod.POST)
	public Boolean bindSnsAccount(HttpServletRequest request,@RequestBody Map<String, String> params){

		String oldPassword = StringUtils.trimToEmpty(params.get("oldPassword"));
		UserEntity userEntity = userMapper.selectByPrimaryKey(SecurityUtil.getLoginUserId());
		if(!userEntity.getPassword().equals(PasswordUtils.encrypt(oldPassword, userEntity.getUsername()))){
			throw new JeesuiteBaseException(4001, "原密码错误");
		}
		userEntity.setPassword(StringUtils.trimToEmpty(params.get("password")));
		userService.updateUser(userEntity);
		
		return true;
	}
	
	@RequestMapping(value = "upload_avatar", method = RequestMethod.POST)
	public @ResponseBody Map<String, String> uploadConfigFile(@RequestParam("file") MultipartFile file){
		ByteArrayOutputStream outputStream = null;
		try {
			
			Map<String, String> result = new HashMap<>();
			
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			if(!allow_upload_suffix.contains(suffix.toLowerCase())){
				throw new JeesuiteBaseException(9999, "不允许上传该文件类型");
			}
			
			int loginUserId = SecurityUtil.getLoginUserId();
			String savepath = buildAvatarPath(loginUserId);
			
			
			byte[] bytes = file.getBytes();
			if(!PNG.equalsIgnoreCase(suffix)){
				BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
				outputStream = new ByteArrayOutputStream();
				ImageIO.write(bim, PNG, outputStream);
				bytes = outputStream.toByteArray();
			}
			
			String url = provider.upload("avatar", savepath, bytes, FileType.PNG);
			
            UserEntity userEntity = new UserEntity();
            userEntity.setId(loginUserId);
            userEntity.setAvatar(url);
            
            userService.updateUser(userEntity);
            
            result.put("url", url);
            
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new JeesuiteBaseException(9999, "修改失败");
		}finally {
			try {if(outputStream != null)outputStream.close(); } catch (Exception e2) {}
		}
	}
	
	private String buildAvatarPath(int userId){
		String leve1Dir = String.valueOf(userId % 100);
		return String.format("/%s/%s.png", leve1Dir,userId);
	}
	

}
